using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;

public class ShoubanResult
{
    //public int totalCount;
    //public int goUpCount;
    public float averGoUpRate;
}

public class ShoubanAnalysis : BatchProcessor
{
    /// <summary>
    /// 筛选的股价最大值
    /// </summary>
    const float maxPrice = 26;
    /// <summary>
    /// 需要的近三月最少涨停次数
    /// </summary>
    const int needGoUpTopCount = 2;
    private static string shoubanOutputDir(int fromYear)  => StockDataAnalysis.dataOutputDir + $"Shouban/{fromYear}_{System.DateTime.Now.Year}/";
    public static string shoubanOutputPath(int fromYear, string stockCode) => shoubanOutputDir(fromYear) + $"{stockCode}.json";
    public int fromYear => AppController.instance.StockDataAnalysis.fromYear;
  
    #region test
    [NonSerialized]
    private StockAllData m_stockAllData;
    StockAllData testStockData
    {
        get
        {
            if (m_stockAllData == null || m_stockAllData.stockTransitions == null)
            {
                m_stockAllData = StocksDataController.instance.GetStockAllData(testStock,fromYear);
            }
            return m_stockAllData;
        }
    }
    public string testStock = "000001";

    // [ContextMenu("TestFindShouban")]
    // void TestFindYijianfenghou()
    // {
    //     var yijianfenghou = FindShouban(testStockData);
    //     if (yijianfenghou != null && yijianfenghou.transitionsRanges != null && yijianfenghou.transitionsRanges.Count > 0)
    //     {
    //         var result = AnalysisShoubanResult(yijianfenghou);
    //         Debug.LogError(
    //             $"${testStockData.stockData.dm} 的一剑封喉波段有{JsonConvert.SerializeObject(yijianfenghou)}, 入场后3天平均上涨：{result.averGoUpRate}");
    //     }
    //     else
    //     {
    //         Debug.LogError($"${testStockData.stockData.dm} 找不到一剑封喉波段");
    //     }
    // }
    #endregion
    
    // [ContextMenu("FindAllStocksShouban")]
    // void FindAllStocksShouban()
    // {
    //     m_totalGoUpRate = 0;
    //     m_totalFoundCount = 0;
    //     actionInterval = 0.01f;
    //     DoActionToAllStocks(DoFindShouban);
    // }
    //
    // private int m_totalFoundCount;
    // private int m_goUpCount;
    // float m_totalGoUpRate = 0;
    // private float averGoUpRate;
    // void DoFindShouban(StockData stock)
    // {
    //     var stockAllData = StocksDataController.instance.GetStockAllData(stock.dm,fromYear);
    //     var shouban = FindShouban(stockAllData);
    //     if (shouban != null && shouban.transitionsRanges != null && shouban.transitionsRanges.Count > 0)
    //     {
    //         var result = AnalysisShoubanResult(shouban);
    //         Debug.Log($"${stock.dm} 的首版波段有{JsonConvert.SerializeObject(shouban)}, 入场后3天平均上涨：{result.averGoUpRate}");
    //         
    //         string str = JsonConvert.SerializeObject(shouban);
    //         //Debug.Log(str);
    //         File.WriteAllText(shoubanOutputPath(fromYear, stock.dm), str);
    //
    //         m_totalGoUpRate += result.averGoUpRate;
    //         if (result.averGoUpRate > 0)
    //             m_goUpCount++;
    //         m_totalFoundCount++;
    //     }
    // }
    protected override void onCompleted()
    {
        // if (m_totalFoundCount > 0)
        // {
        //     float goUpPercentage = (float) m_goUpCount / m_totalFoundCount;
        //     float averGoUpRate = m_totalGoUpRate / m_totalFoundCount;
        //     string content =
        //         $"{m_totalFoundCount} 个一剑封喉波段,入场后2天上涨的有{m_goUpCount}个，上涨概率为：{goUpPercentage}, 平均上涨：{averGoUpRate}";
        //     Debug.LogError(content);
        //     onEnd?.Invoke(content);
        // }
        // else 
        if (m_pickedStocks != null)
        {
            string content = JsonConvert.SerializeObject(m_pickedStocks);
            Debug.LogError($"选出的首板股票有：{content}");
            onEnd?.Invoke(content);
        }
    }
    async Task<StockTransitionsRanges> FindShouban(StockAllData stock)
    {
        Debug.Log($"FindYijianfenghou:{stock.stockData.dm}");

        if (!Directory.Exists(shoubanOutputDir(fromYear)))
        {
            Directory.CreateDirectory(shoubanOutputDir(fromYear));
        }

         var stockAllData = StocksDataController.instance.GetStockAllData(stock.stockData.dm, fromYear);
        if (stockAllData == null || stockAllData.stockTransitions == null)
            return null;

        var yijianfenghou = new StockTransitionsRanges();
        yijianfenghou.stockCode = stock.stockData.dm;
        yijianfenghou.transitionsRanges = new List<TransitionsRange>();
        
        var transitions = stockAllData.stockTransitions;

        if (transitions.Count < 4)
            return null;

        var cur = transitions[^1];
        var pre = transitions[^2];
        var qian = transitions[^3];
        var qian2 = transitions[^4];
        
        //股价小于25
        if (cur.c > maxPrice)
        {
            return null;
        }

        //首板
        bool goUpTop = (cur.c - pre.c) / pre.c > 0.096f;
        if (!goUpTop)
        {
            return null;
        }
        
        bool preGoUpTop = (qian.c - qian2.c) / qian2.c > 0.096f;
        if (preGoUpTop)
        {
            //Debug.Log($"{stock.stockData.dm} 非首板");
            return null;
        }

        var nowTime = System.DateTime.Parse(cur.d);
        //Debug.Log($"当前时间：{nowTime}");

        //近三个月涨停次数大于等于2
        int goUpTopCount = 0;
        for (int k = transitions.Count - 70; k < transitions.Count - 2; k++)
        {
            var time = System.DateTime.Parse(transitions[k].d);
            if (nowTime.DayOfYear - time.DayOfYear > 90)
            {
                //Debug.Log($"ignore:{JsonConvert.SerializeObject(transitions[k])}");
                continue;
            }

            int preDay = k - 1;
            if(preDay < 0)
                continue;
            
            bool isGoUpTop = (transitions[k].c - transitions[preDay].c) / transitions[preDay].c > 0.096f;
            if (isGoUpTop)
            {
                goUpTopCount++;
                if (goUpTopCount >= needGoUpTopCount)
                {
                    break;
                }
            }
        }
        if (goUpTopCount < needGoUpTopCount)
        {
            Debug.Log($"{stock.stockData.dm} 近三月涨停次数少于2");
            return null;
        }
        
        //流通市值小于100亿，
        //CompanyFundInfo info  = await BYAPIDataController.instance.RequestCompanyFundInfo(stock.stockData.dm);
        
        
        //Debug.Log($"选出股");
        var range = new List<TransitionData>();
        for (int k = transitions.Count - 60; k < transitions.Count; k++)
        { 
            var time = System.DateTime.Parse(transitions[k].d);
            if (nowTime.DayOfYear - time.DayOfYear > 90)
            {
                //Debug.Log($"ignore:{JsonConvert.SerializeObject(transitions[k])}");
                continue;
            }
            range.Add(transitions[k]);
        }
        var TransitionsRange = new List<TransitionsRange>(){new TransitionsRange(){transitions = range}};
        yijianfenghou.transitionsRanges = TransitionsRange;
        return yijianfenghou;
    }
    
   
    ShoubanResult AnalysisShoubanResult(StockTransitionsRanges ranges)
    {
        ShoubanResult result = new ShoubanResult();
        if (ranges.transitionsRanges != null && ranges.transitionsRanges.Count > 0)
        {
            double total = 0;
            // foreach (var yijianfenghouRange in ranges.transitionsRanges)
            // {
            //     int endIndex = yijianfenghouRange.ruChangIndex + 2;
            //     if (endIndex >= yijianfenghouRange.transitions.Count)
            //         endIndex = yijianfenghouRange.transitions.Count - 1;
            //     double goUpRate = yijianfenghouRange.transitions[endIndex].c - ruchangDian.c;
            //     total += goUpRate;
            // }

            result.averGoUpRate = (float) total / ranges.transitionsRanges.Count;
        }
        return result;
    }

    

    [ContextMenu("选最近首板股")]
    public void PickAllShouban()
    {
        actionInterval = 0.01f;
        m_pickedStocks = new List<StockData>();
        DoActionToAllStocks(DoPickShouban);
    }

    private List<StockData> m_pickedStocks;
    async void DoPickShouban(StockData stock)
    {
        var stockAllData = StocksDataController.instance.GetStockAllData(stock.dm,fromYear);
        if (stockAllData == null || stockAllData.stockTransitions == null)
            return;
        
        var shouban = await FindShouban(stockAllData);
        if (shouban != null && shouban.transitionsRanges != null && shouban.transitionsRanges.Count > 0)
        {
            Debug.LogError($"选出首板股：{stock.dm} ，波段：{JsonConvert.SerializeObject(shouban)}");
            m_pickedStocks.Add(stock);
        }
    }
}